import 'package:auto_route/auto_route.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/play_orverlay_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:auto_route/auto_route.dart';

@RoutePage()
class LifeOfficialTopicListScreen extends ConsumerStatefulWidget {
  final String subjectId;
  final String title;

  const LifeOfficialTopicListScreen({
    super.key,
    required this.subjectId,
    required this.title,
  });

  @override
  ConsumerState<LifeOfficialTopicListScreen> createState() =>
      _LifeOfficialTopicList();
}

class _LifeOfficialTopicList
    extends ConsumerState<LifeOfficialTopicListScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final contentState = ref.watch(
      lifeTopicListNotifierProvider(widget.subjectId),
    );
    final contentNotifier = ref.watch(
      lifeTopicListNotifierProvider(widget.subjectId).notifier,
    );
    final double bottomPadding = MediaQuery.of(context).padding.bottom + 5.h;

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: widget.title),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            contentNotifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            await contentNotifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(child: SizedBox(height: 12.h)),
              contentState.when(
                loading: () => _buildSliverLoading(),
                error: (e, _) => _buildSliverError(''),
                data: (data) {
                  final items = data.data;
                  if (items!.isEmpty) {
                    return _buildSliverEmpty('暂无内容');
                  }
                  return SliverPadding(
                    padding: EdgeInsets.only(left: 12.w, right: 12.w),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate((context, index) {
                        return buildItem(context, items[index]); // UI 独立封装
                      }, childCount: items.length),
                      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200.w,
                        mainAxisSpacing: 12.w,
                        crossAxisSpacing: 12.w,
                        mainAxisExtent: 230.h,
                      ),
                    ),
                  );
                },
              ),
              SliverToBoxAdapter(child: SizedBox(height: bottomPadding)),
            ],
          ),
        ),
      ),
    );
  }

  // ========= 通用状态 Sliver =========
  SliverToBoxAdapter _buildSliverLoading() => const SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: CommonLoadingWidget()),
    ),
  );

  SliverToBoxAdapter _buildSliverError(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: Text(message)),
    ),
  );

  SliverToBoxAdapter _buildSliverEmpty(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(
        child: Text(
          message,
          style: TextStyle(fontSize: 14.r, color: Colors.grey),
        ),
      ),
    ),
  );

  Widget buildItem(BuildContext context, LifeTopicModule topicModel) {
    return Container(
      width: 170.w,

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: double.infinity,
            height: 180.h,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Stack(
                fit: StackFit.expand,
                children: [
                  CachedNetworkImage(
                    imageUrl: topicModel.coverImg,
                    cacheKey: topicModel.id,
                    fit: BoxFit.cover,
                    fadeInDuration: Duration.zero,
                    placeholder: (context, url) => const SizedBox(),
                    errorWidget: (context, url, error) =>
                        const Icon(Icons.error, color: Colors.red),
                  ),
                  if (topicModel.mediaType == LifeTopicMediaType.video &&
                      topicModel.mediaSrcList.isNotEmpty)
                    PlayOverlayButton(
                      onTap: () =>
                          _handleVideoTap(context, topicModel.mediaSrcList[0]),
                    ),
                ],
              ),
            ),
          ),
          SizedBox(height: 6.h),
          SizedBox(
            width: 170.w,
            child: GestureDetector(
              onTap: () {
                _handleItemClick(topicModel);
              },
              child: Text(
                topicModel.title,
                textAlign: TextAlign.left,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: context.textTheme.bodyMedium!.copyWith(
                  color: context.customColorThemeNonNull.textColor1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _handleItemClick(LifeTopicModule item) {
    context.router.push(LifeTopicDetailRoute(topicId: item.id));
  }

  void _handleVideoTap(BuildContext context, String url) {
    if (url.isEmpty) return;
    context.router.push(VideoPlayerRoute(url: url, title: ''));
  }
}
